<?php
class DefaultModuleController extends base {
	
	public $userId = 0;
	public $userName;
	public $groupId;
	public $user = array();
	
	public function init() {
		// 用户相关
		$this->userId = $this->getState('userId');
		if($this->userId) {
			$this->userName = $this->getState('userName');
			$this->groupId = $this->getState('groupId');

			$this->user = $this->UserModel->findByPk($this->userId);
			$userGroup = $this->UserGroupModel->findByPk($this->groupId);
			$cartCount = $this->ShoppingcartModel->sumCount("userId='".$this->userId."' AND settleStatus=0", 'cartCount');
			
			$this->user = array_merge($this->user, $userGroup);
			// 格式化用户信息
			//$this->user['discount'] = $this->user['discount']/100;
			$this->user['cartCount'] = intval($cartCount);

			$this->view->assign('userInfo', $this->user);
		} else {
			$this->user['cartCount'] = 0;
		}
		
		// 导航显示
		$navNameArr = array( 'product'=>'产品中心', 'gifts'=>'积分礼品', 'user'=>'用户中心', 'news'=>'新闻中心');
		
		//分类下拉菜单		
		$mlistArr = $optionListArr = array();
		$listArr = $this->CategorysPublic->get_list(GODHOUSE_CATEGORY_PRODUCT, 2);
		$i = 0;
		foreach($listArr as $key => $val) {
			if($val['level'] < 3) {
				$optionListArr[] = array('categoryId' => $val['categoryId'].'_'.$val['level'], 'cateName' => str_repeat('　', $val['level']) . '├ ' . $val['cateName']);
			}
			if($val['level']==1) {
				$i++;
				$j = -1;
				$strArr = array();				
				foreach ($listArr as $okey => $oval) {				
					if($oval['parentId']==$val['categoryId']) {
						$j++;
						$strArr[] = array('categoryId' => $oval['categoryId'], 'cateName' => $oval['cateName'], 'productCount' => $oval['child']);
					}
				}
				$mlistArr[] = array('styleSwitch' => $i%2, 'categoryId' => $val['categoryId'], 'cateName' => $val['cateName'], 'okey' => $j, 'moreArr' => $strArr);
			}
		}
		unset($listArr);

		$navName = isset($navNameArr[getgpc('c')]) ? ' > '.$navNameArr[getgpc('c')] : '';
		
		// 显示产品大列数据
		$navProductList = $this->CategoryModel->findAll("parentId='0' AND storeId='".GODHOUSE_CATEGORY_PRODUCT."'");
		
		$categoryId = getgpc('categoryId');
		
		
		
		$this->view->assign('userInfo', $this->user);
		$this->view->assign('navName', $navName);
		$this->view->assign('Category', $categoryId);
		$this->view->assign('optionListArr', $optionListArr);
		$this->view->assign('listArr', $mlistArr);
		$this->view->assign('navProductList', $navProductList);
	}
	
	//$num=总页数, $perpage=每页显示数量，$curpage=当前所在页，$mpurl=页面链接
	public function page($num, $perpage, $curpage, $mpurl) { 	
		$multipage = '';
		$mpurl .= strpos ( $mpurl, '?' ) ? '&' : '?';
		
		if($num > $perpage) {
			$page = 6;
			$offset = 2;			
			$pages = @ceil ( $num / $perpage );
					
			if($page > $pages) {
				$from = 1;
				$to = $pages;
			} else {
				$from = $curpage - $offset;
				$to = $from + $page - 1;
				if($from < 1) {
					$to = $curpage + 1 - $from;
					$from = 1;
					if ($to - $from < $page) $to = $page;				
				}elseif($to > $pages) {
					$from = $pages - $page + 1;
					$to = $pages;
				}
			}
			
			$simple = '0';
			$realpages = $pages;
			$multipage = ($curpage > 1 ? '<a href="' . $mpurl . 'page=' . ($curpage - 1) . '" >上一页</a>' : '') . ($curpage - $offset > 1 && $pages > $page ? '<a href="' . $mpurl . 'page=1">首页</a>' : '');
			
			for($i = $from; $i <= $to; $i ++) {
				$multipage .= $i == $curpage ? '<span class="current">' . ($i < 10 ? '0' . $i : $i) . '</span>' : '<a href="' . $mpurl . 'page=' . $i . ($i == $pages ? '' : '') . '">' . ($i < 10 ? '0' . $i : $i) . '</a>';
			}
					
			$multipage .= ($to < $pages ? '<a href="' . $mpurl . 'page=' . $pages . '">尾页</a>' : '') . ($curpage < $pages  ? '<a href="' . $mpurl . 'page=' . ($curpage + 1) . '">下一页</a>' : '') . (! $simple && $pages > $page ? $perpage . '条/页&nbsp;<kbd>转到第<input type="text" name="custompage" id="custompage" size="3" value="'.$curpage.'" onkeydown="if(event.keyCode==13) {window.location=\''.$mpurl.'page=\'+this.value; return false;}" />页<input type="button" value="跳转" onclick="window.location=\''.$mpurl.'page=\'+$(\'custompage\').value;" /></kbd>' : '');
			$multipage = $multipage ? "总共有<b>{$num}</b>条数据&nbsp;" . $multipage . '' : '';
		}		
		return $multipage;
	}
	
	protected function setStateInfo($user, $expiresTime) {
		//echo $expiresTime;exit;
		$this->setState('userId', $user['userId'], $expiresTime);
		$this->setState('userName', $user['userName'], $expiresTime);
		$this->setState('groupId', $user['groupId'], $expiresTime);
	}
	
	/**
	 * 获取产品的折扣
	 *
	 * @param unknown_type $upperparentId 二级分类 ID
	 * @param unknown_type $parentId 一级分类Id
	 */
	protected function getDiscount($upperparentId=0, $parentId=0) {
		$discount = 100;
		$discounts = array();
		$discountList = $this->DiscountModel->findAll("categoryId='$parentId'");
		if($discountList) {
			foreach($discountList as $v) {
				if($this->user['groupId'] == $v['groupId']) {
					$discount = $v['discountRate'];
				}
			}
		} else {
			$discountList2 = $this->DiscountModel->findAll("categoryId='$upperparentId'");
			if($discountList2) {
				foreach($discountList2 as $v) {
					if($this->user['groupId'] == $v['groupId']) {
						$discount = $v['discountRate'];
					}
				}
			}
		}
		$discount = $discount/100;
		return $discount;
	}
	
	protected function _totalPrice( $where = '' ) {
		$totalPrice = $cartCount = $offerPriceSum = 0;
		if(!empty($where)) {
			$sql = "SELECT a.id AS cartId,a.productId,a.cartCount,a.discount,a.ourPrice,a.promotionsPrice,a.ispromotions,b.productNo,b.content FROM god_shoppingcart AS a JOIN god_product as b on a.productId = b.productId WHERE $where";
		} else {
			$sql = "SELECT a.id AS cartId,a.productId,a.cartCount,a.discount,a.ourPrice,a.promotionsPrice,a.ispromotions,b.productNo,b.content FROM god_shoppingcart AS a JOIN god_product as b on a.productId = b.productId WHERE a.userId = '$this->userId' AND a.settleStatus=0";
		}
		$shopCartArr = $this->db->fetch_all($sql);
		foreach($shopCartArr as &$v) {			
			if($v['ispromotions']==0) {
				$v['userPrice'] = number_format($v['ourPrice']*$v['discount'], 2, '.', '');//会员价格
				$v['promotions'] = '';
			} else {
				$v['userPrice'] = number_format($v['promotionsPrice'], 2, '.', '');//折扣价格
				$v['promotions'] = '<font color=red>【促销】</font>';
			}
			
			$v['contents'] = cutstr($v['content'], '16', '');
			$v['totalPrice'] = number_format($v['ourPrice']*$v['discount']*$v['cartCount'], 2, '.', '');//小计		
			$v['offerPrice'] = number_format(number_format($v['ourPrice']*$v['cartCount'],2,'.','')-$v['totalPrice'], 2, '.', '');//优惠
			
			$totalPrice += $v['totalPrice'];//会员商品总价
			$cartCount += $v['cartCount'];//商品总数量
			$offerPriceSum += $v['offerPrice'];//总优惠价
		}
		return array(
				'shopCartArr'=>$shopCartArr,
				'totalPrice'=>number_format($totalPrice, 2, '.', ''),
				'offerPriceSum'=>number_format($offerPriceSum, 2, '.', ''),
				'cartCount'=>$cartCount
			);
	}
}